<template>
  <div class="event-review-container">
    <div class="controls">
      <button @click="activateCircleQuery" :class="{ active: queryMode === 'circle' }">圆框查询事件</button>
      <button @click="clearQueryResults">清除查询</button>
      <button @click="toggleHeatmap" v-if="queriedEvents.length > 0">
        {{ heatmapVisible ? '隐藏热力图' : '显示热力图' }}
      </button>
    </div>

    <div v-if="queryMode === 'circle' && !querying" class="info-text">
      请在地图上点击并拖动以绘制查询范围。
    </div>

    <div v-if="queriedEvents.length > 0 && !heatmapVisible" class="results-container">
      <h4>查询结果 ({{ queriedEvents.length }} 条)</h4>
      <div class="event-list">
        <ul>
          <li v-for="event in queriedEvents" :key="event.id" @click="panToEvent(event)">
            <strong>{{ event.name }}</strong> ({{ event.type }})
            <p>{{ event.description }}</p>
          </li>
        </ul>
      </div>
      <div class="chart-container">
        <h5>事件类型统计</h5>
        <canvas id="eventStatsChart"></canvas>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, onMounted, onUnmounted, watch, nextTick } from 'vue';
import Chart from 'chart.js/auto'; // 引入 Chart.js
// 假设 OpenLayers (ol) 是全局引入的

const map = inject('mapInstance', ref(null));
const drawInteraction = ref(null);
const queryLayer = ref(null); // 用于显示查询范围和结果
const heatmapLayer = ref(null);
const queriedEvents = ref([]);
const queryMode = ref(''); // 'circle'
const querying = ref(false); // 是否正在进行绘制查询
const heatmapVisible = ref(false);
let eventStatsChart = null;

// 模拟的已保存事件数据，实际应用中应从后端API获取
// 确保事件数据包含几何信息 (例如 GeoJSON 格式的 geometry)
const mockSavedEvents = [
  {
    id: 'evt001', name: '中山路口追尾', type: '交通事故', description: '两车追尾，无人员伤亡',
    geometry: { type: 'Point', coordinates: ol.proj.fromLonLat([114.305, 30.500]) }
  },
  {
    id: 'evt002', name: '光谷大道施工', type: '道路施工', description: '道路封闭一半，请绕行',
    geometry: { type: 'LineString', coordinates: [ol.proj.fromLonLat([114.310, 30.505]), ol.proj.fromLonLat([114.312, 30.506])] }
  },
  {
    id: 'evt003', name: '软件园路段拥堵', type: '拥堵', description: '早高峰严重拥堵',
    geometry: { type: 'Point', coordinates: ol.proj.fromLonLat([114.300, 30.510]) }
  },
  {
    id: 'evt004', name: '雄楚大道事故', type: '交通事故', description: '三车连撞，交通中断',
    geometry: { type: 'Point', coordinates: ol.proj.fromLonLat([114.290, 30.490]) }
  },
  // 更多事件...
];

const createQueryLayer = () => {
  if (!map.value) return null;
  if (queryLayer.value) {
    map.value.removeLayer(queryLayer.value);
  }
  const source = new ol.source.Vector();
  const layer = new ol.layer.Vector({
    source: source,
    style: new ol.style.Style({
      fill: new ol.style.Fill({ color: 'rgba(0, 153, 255, 0.1)' }),
      stroke: new ol.style.Stroke({ color: '#0099ff', width: 2 }),
      image: new ol.style.Circle({
        radius: 5,
        fill: new ol.style.Fill({ color: '#0099ff' }),
        stroke: new ol.style.Stroke({ color: 'white', width: 1 })
      })
    }),
    title: 'QueryLayer',
  });
  map.value.addLayer(layer);
  return layer;
};

const activateCircleQuery = () => {
  if (!map.value) {
    console.warn('地图实例未提供');
    return;
  }
  clearQueryResults(); // 开始新的查询前清除旧结果
  queryMode.value = 'circle';
  querying.value = true;

  if (drawInteraction.value) {
    map.value.removeInteraction(drawInteraction.value);
  }
  if (!queryLayer.value) {
    queryLayer.value = createQueryLayer();
  }

  drawInteraction.value = new ol.interaction.Draw({
    source: queryLayer.value.getSource(), // 绘制在查询图层上
    type: 'Circle',
  });

  drawInteraction.value.on('drawend', (event) => {
    querying.value = false;
    const circleGeometry = event.feature.getGeometry();
    performQuery(circleGeometry);
    map.value.removeInteraction(drawInteraction.value);
    drawInteraction.value = null;
    // 保留绘制的圆圈在图上，或者在 performQuery 后清除
    // queryLayer.value.getSource().clear(); // 如果不想保留绘制的圆
  });

  map.value.addInteraction(drawInteraction.value);
};

const performQuery = (queryGeometry) => {
  queriedEvents.value = mockSavedEvents.filter(event => {
    const eventFeature = new ol.format.GeoJSON().readFeature({ type: 'Feature', geometry: event.geometry });
    const eventGeom = eventFeature.getGeometry();
    if (queryGeometry.intersectsCoordinate(eventGeom.getCoordinates ? eventGeom.getCoordinates() : eventGeom.getFirstCoordinate())) {
        return true;
    }
    // 对于线和面，可能需要更复杂的相交判断
    // ol.extent.intersects(queryGeometry.getExtent(), eventGeom.getExtent())
    return false; // 简化处理，实际需要根据 geometry 类型判断
  });

  console.log('查询到的事件:', queriedEvents.value);
  if (queryLayer.value) {
    queriedEvents.value.forEach(event => {
        const feature = new ol.format.GeoJSON().readFeature({ type: 'Feature', geometry: event.geometry, properties: event });
        queryLayer.value.getSource().addFeature(feature);
    });
  }
  updateChart();
};

const clearQueryResults = () => {
  queriedEvents.value = [];
  if (queryLayer.value) {
    queryLayer.value.getSource().clear();
  }
  if (drawInteraction.value && map.value) {
    map.value.removeInteraction(drawInteraction.value);
    drawInteraction.value = null;
  }
  if (heatmapLayer.value && map.value) {
    map.value.removeLayer(heatmapLayer.value);
    heatmapLayer.value = null;
    heatmapVisible.value = false;
  }
  queryMode.value = '';
  querying.value = false;
  destroyChart();
};

const panToEvent = (eventItem) => {
  if (map.value && eventItem.geometry && eventItem.geometry.coordinates) {
    let centerCoord;
    if (eventItem.geometry.type === 'Point') {
        centerCoord = eventItem.geometry.coordinates;
    } else if (eventItem.geometry.type === 'LineString') {
        centerCoord = eventItem.geometry.coordinates[0]; // 取线的第一个点
    } // 可为 Polygon 添加类似逻辑

    if (centerCoord) {
        map.value.getView().animate({
            center: centerCoord, // 已经是地图投影坐标
            zoom: 16,
            duration: 800,
        });
    }
  }
};

const updateChart = async () => {
  await nextTick(); // 等待 DOM 更新
  destroyChart();
  if (queriedEvents.value.length === 0) return;

  const ctx = document.getElementById('eventStatsChart');
  if (!ctx) return;

  const stats = queriedEvents.value.reduce((acc, event) => {
    acc[event.type] = (acc[event.type] || 0) + 1;
    return acc;
  }, {});

  eventStatsChart = new Chart(ctx, {
    type: 'bar', // 或 'pie', 'doughnut'
    data: {
      labels: Object.keys(stats),
      datasets: [{
        label: '事件数量',
        data: Object.values(stats),
        backgroundColor: [
          'rgba(255, 99, 132, 0.5)',
          'rgba(54, 162, 235, 0.5)',
          'rgba(255, 206, 86, 0.5)',
          'rgba(75, 192, 192, 0.5)',
          'rgba(153, 102, 255, 0.5)',
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
        ],
        borderWidth: 1,
      }],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: true,
          ticks: { stepSize: 1 }
        },
      },
    },
  });
};

const destroyChart = () => {
  if (eventStatsChart) {
    eventStatsChart.destroy();
    eventStatsChart = null;
  }
};

const toggleHeatmap = () => {
  if (!map.value || queriedEvents.value.length === 0) return;

  heatmapVisible.value = !heatmapVisible.value;

  if (heatmapVisible.value) {
    if (heatmapLayer.value) map.value.removeLayer(heatmapLayer.value);

    const features = queriedEvents.value.map(event => {
      // 热力图通常基于点数据
      let pointGeometry;
      if (event.geometry.type === 'Point') {
        pointGeometry = new ol.geom.Point(event.geometry.coordinates);
      } else if (event.geometry.type === 'LineString') {
        // 对线状事件，可以取其中心点或首点作为热力图输入
        pointGeometry = new ol.geom.Point(event.geometry.coordinates[0]);
      } else {
        return null; // 不支持的面状事件，或取其质心
      }
      return new ol.Feature({ geometry: pointGeometry, weight: Math.random() }); // weight 可以基于事件严重程度等
    }).filter(f => f !== null);

    if (features.length === 0) {
        heatmapVisible.value = false;
        alert('没有可用于生成热力图的点数据。');
        return;
    }

    heatmapLayer.value = new ol.layer.Heatmap({
      source: new ol.source.Vector({ features }),
      blur: 15,
      radius: 10,
      title: 'EventHeatmapLayer',
      // weight: function(feature) { return feature.get('weight'); } // 如果 weight 存储在 feature属性中
    });
    map.value.addLayer(heatmapLayer.value);
    if (queryLayer.value) queryLayer.value.setVisible(false); // 查询结果图层可以隐藏

  } else {
    if (heatmapLayer.value) map.value.removeLayer(heatmapLayer.value);
    heatmapLayer.value = null;
    if (queryLayer.value) queryLayer.value.setVisible(true); // 重新显示查询结果图层
  }
};

onMounted(() => {
  // 初始化时可以不创建图层，等待用户操作
});

onUnmounted(() => {
  if (map.value && drawInteraction.value) {
    map.value.removeInteraction(drawInteraction.value);
  }
  if (map.value && queryLayer.value) {
    map.value.removeLayer(queryLayer.value);
  }
  if (map.value && heatmapLayer.value) {
    map.value.removeLayer(heatmapLayer.value);
  }
  destroyChart();
});

watch(() => map.value, (newMap) => {
  if (newMap && !queryLayer.value && queryMode.value) {
    // 如果地图加载后，且之前有查询模式，可以重新激活
    // activateCircleQuery(); // 或者其他查询模式
  }
});

</script>

<style scoped lang="scss">
.event-review-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 5px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 0 5px;
  max-height: 400px; /* 限制最大高度，内容超出可滚动 */
  overflow-y: auto;
}

.controls {
  display: flex;
  gap: 5px;
  margin-bottom: 10px;
  flex-wrap: wrap; /* 按钮换行 */
  button {
    padding: 6px 10px;
    background-color: #337ab7; /* 蓝色，表示查询/信息 */
    color: white;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    font-size: 12px;
    &.active {
      background-color: #286090;
      box-shadow: inset 0 1px 3px rgba(0,0,0,0.2);
    }
    &:hover {
      background-color: #2e6da4;
    }
  }
}

.info-text {
  font-size: 12px;
  color: #555;
  padding: 5px 0;
}

.results-container {
  width: 100%;
  h4 {
    margin-top: 0;
    margin-bottom: 10px;
    font-size: 14px;
    color: #333;
  }
}

.event-list {
  max-height: 150px;
  overflow-y: auto;
  margin-bottom: 15px;
  border: 1px solid #eee;
  padding: 5px;
  ul {
    list-style: none;
    padding: 0;
    margin: 0;
    li {
      padding: 8px 5px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      font-size: 12px;
      &:last-child {
        border-bottom: none;
      }
      &:hover {
        background-color: #f9f9f9;
      }
      strong {
        display: block;
        color: #007bff;
      }
      p {
        font-size: 11px;
        color: #666;
        margin: 3px 0 0 0;
      }
    }
  }
}

.chart-container {
  height: 200px; /* 固定图表高度 */
  width: 100%;
  canvas {
    max-width: 100%;
  }
  h5 {
      margin-top: 0;
      margin-bottom: 5px;
      font-size: 13px;
      text-align: center;
  }
}
</style>